package com.dream.inspect.modules.app.controller.common;


import com.dream.inspect.common.utils.DatetimeUtil;
import com.dream.inspect.common.utils.FileUtil;
import com.dream.inspect.common.utils.R;
import com.dream.inspect.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "/app/common/file")
public class FileController {
    @Value("${config.winReporterPath}")
    private String winPath;
    @Value("${config.linuxReporterPath}")
    private String linuxPath;

    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public R uploadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file") MultipartFile[] files) {
        try {
            String newFileNames = "";
            if (files == null || files.length == 0) {
                throw new Exception("没有选择上传文件");
            }else if(files.length == 1){
                newFileNames = this.uploadOneFileList(files[0], request);
            }else{
                newFileNames = this.uploadFileList(files, request);
            }


        /*for(int i=0;i<graphTheories.length;i++){
             String filename=graphTheories[i].getOriginalFilename();
             System.out.println(filename);
         }*/
            return R.ok().put("filePath",newFileNames);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    /**
     * 封装公共的文件下载方法，
     *
     * @param path     文件的绝对路径，包括文件名
     * @param type     类型，0跟null为加密，其它为URL不用URLENCODER 加密
     * @param response 返回体
     * @return
     */
    @RequestMapping("downloadfile")
    public void download(String path, String type, HttpServletResponse response, HttpServletRequest request) {
        OutputStream toClient = null;
        InputStream fis = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String filePath;
            if (type == null || "0".equals(type)) {
                filePath = URLDecoder.decode(path,"UTF-8");
            } else {
                filePath = path;
            }
            // path是指欲下载的文件的路径。
            File file = new File(filePath);
            // 取得文件名。
            // String filename = URLEncoder.encode(file.getName(),
            // AttrConstants.UTF8);
            String fileName = file.getName();
            fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20"); // IE下载文件名空格变+号问题
            } else {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName); // new
            // String(filename.getBytes(),
            // AttrConstants.UTF8)
            response.addHeader("Content-Length", "" + file.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
//            toClient.write(buffer);
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (toClient != null) {
                    toClient.flush();
                    toClient.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("getImgByPath")
    public void getImgByPath(HttpServletRequest request, HttpServletResponse response,String path) {
        if (StringUtil.isNotEmpty(path) && (path.toLowerCase().endsWith(".jpg") || path.toLowerCase().endsWith(".png") || path.toLowerCase().endsWith(".JPG") || path.toLowerCase().endsWith(".PNG"))) {
            /*
             * try { path = URLDecoder.decode(path,"UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); }
             */
            InputStream is = null;
            OutputStream os = null;
            try {
                File file = new File(path);
                if (!file.exists()) return;
                else is = FileUtil.byte2Input(FileUtil.file2byte(path));
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 1024];
                while ((count = is.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (os != null) {
                        os.close();
                    }
                    response.flushBuffer();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }

    }


    public String uploadOneFileList(MultipartFile multipartFile, HttpServletRequest request) throws Exception {
        List<String> newFileNames = new ArrayList<>();
        String os = System.getProperty("os.name");
        String newPath = null;
        //String newFileName = null;
        //newFileName = UUID.randomUUID() + originalFilename;
        String today = DatetimeUtil.getDateyyyyMMddhhmmss();
        if (os.toLowerCase().startsWith("win")) {
            newPath = winPath + "img/" + today + "/";
        } else {
            newPath = linuxPath + "img/" + today + "/";
        }
        try {
                //文件的原始名称
                String originalFilename = multipartFile.getOriginalFilename();
                //
                if (multipartFile != null && originalFilename != null && originalFilename.length() > 0) {

                    //存储图片的物理路径
                    //String pic_path = request.getSession().getServletContext().getRealPath("/upload");
                    //如果文件夹不存在则创建
                    File file = new File(newPath);
                    if (!file.exists()) {
                        System.out.println("file not exists");
                        file.mkdirs();
                    }
                    /**
                     * 获取新文件的File实例,通过spring的org.springframework.web.multipartInterface MultipartFile
                     * 下的transferTo方法,这个可以移动文件的文件系统,复制文件系统中的文件或内存内容保存到目标文件.
                     * 如果目标文件已经存在,它将被删除。
                     */
                    //新文件路径实例
                    File targetFile = new File(newPath, originalFilename);
                    //内存数据读入磁盘
                    multipartFile.transferTo(targetFile);
                    newFileNames.add(originalFilename);
                }
            return newPath+originalFilename;
        } catch (IOException e) {
            throw new Exception();
        }
    }


    /**
     * 批量上传文件 返回值为文件夹 UUID.randomUUID()+originalFilename
     *
     * @param multipartFiles
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public String uploadFileList(MultipartFile multipartFiles[], HttpServletRequest request) throws Exception {
        List<String> newFileNames = new ArrayList<>();
        String os = System.getProperty("os.name");
        String newPath = null;
        //String newFileName = null;
        //newFileName = UUID.randomUUID() + originalFilename;
        String today = DatetimeUtil.getDateyyyyMMddhhmmss();
        if (os.toLowerCase().startsWith("win")) {
            newPath = winPath + "img/" + today + "/";
        } else {
            newPath = linuxPath + "img/" + today + "/";
        }

        try {
            for (MultipartFile multipartFile : multipartFiles) {
                //文件的原始名称
                String originalFilename = multipartFile.getOriginalFilename();
                //
                if (multipartFile != null && originalFilename != null && originalFilename.length() > 0) {

                    //存储图片的物理路径
                    //String pic_path = request.getSession().getServletContext().getRealPath("/upload");
                    //如果文件夹不存在则创建
                    File file = new File(newPath);
                    if (!file.exists()) {
                        System.out.println("file not exists");
                        file.mkdirs();
                    }
                    /**
                     * 获取新文件的File实例,通过spring的org.springframework.web.multipartInterface MultipartFile
                     * 下的transferTo方法,这个可以移动文件的文件系统,复制文件系统中的文件或内存内容保存到目标文件.
                     * 如果目标文件已经存在,它将被删除。
                     */
                    //新文件路径实例
                    File targetFile = new File(newPath, originalFilename);
                    //内存数据读入磁盘
                    multipartFile.transferTo(targetFile);
                    newFileNames.add(originalFilename);
                }
            }
            return newPath;
        } catch (IOException e) {
            throw new Exception();
        }
    }
}
